import MessageBoxEl from "./messageBox.vue"

import { App, Component, createApp, DefineComponent, ref, watch } from "vue"


interface Options {
    field?: string,
    confirmBtnText?: string,
    showCancelBtn?: boolean,
    cancelBtnText?: string,
    title?: string,
    content?: string
}

let types = ["confirm", "prompt"]

export const MessageBox: any = (options: Options) => {
    let vnode = createApp(MessageBoxEl, { ...options })
    return new Promise((resolve, reject) => {
        showMessageBox(vnode, { resolve, reject })
    })
}

const showMessageBox = (app: App, { resolve, reject }:any) => {
    let oFrag = document.createDocumentFragment()
    let vm: any = app.mount(oFrag)
    document.body.appendChild(oFrag)
    vm.setVisible(true)

  
    watch(()=>vm.state, (state) => {

        if (!state.visible) {
          switch(state.btnType){
            case "confirm":
                resolve(state.promptValue);
                break
            case "cancel":
                reject()
                break
            default:
                break
          }

          hideMessageBox(app,vm)
        }
    },{deep:true})
  
    
}

const hideMessageBox = (app:App,vm:any)=>{
  vm.timer =  setTimeout(() => {
        app.unmount()
        clearTimeout(vm.timer)
        vm.timer = null
    }, 300);
}

types.forEach((field) => {
    MessageBox[field] = (options: Options) => {
        options.field = field

        return MessageBox(options)
    }
})

